package com.lcj.hub.common.handler;

import com.lcj.hub.common.Result;
import com.lcj.hub.common.config.IpConfig;
import com.lcj.hub.common.constant.ErrorCode;
import com.lcj.hub.common.utils.IPUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.io.PrintWriter;

@Component
@Slf4j
public class IpInterceptor implements HandlerInterceptor {

    private final IpConfig ipConfig;

    // 注入 IpConfig
    public IpInterceptor(IpConfig ipConfig) {
        this.ipConfig = ipConfig;
    }

    @Override
    public boolean preHandle(@NonNull HttpServletRequest request,
                             @NonNull HttpServletResponse response,
                             @NonNull Object handler
    ) throws Exception {
        String remoteIp = IPUtils.getIpAddr(request);
        String requestUri = request.getRequestURI();

        log.info("<============== Request from IP: {}, requestUri: {} ==============>", remoteIp, requestUri);
        // 黑名单检查
        if (ipConfig.getBlacklist().contains(remoteIp)) {
            respondWithForbidden(response, ErrorCode.NO_AUTH);
            log.info("<============== ip: {} is in blacklist, access denied ==============>", remoteIp);
            return false;
        }

        // 特殊接口的白名单检查
        if (isSpecialUri(requestUri)) {
            if (ipConfig.getWhitelist().contains(remoteIp)) {
                log.info("<============== ip: {} is in whitelist ==============>", remoteIp);
                return true;
            } else {
                respondWithForbidden(response, ErrorCode.NO_AUTH);
                log.info("<============== ip: {} is not in whitelist, access denied ==============>", remoteIp);
                return false;
            }
        }
        return true;
    }

    private boolean isSpecialUri(String uri) {
        // 定义特殊接口的 URI 判断逻辑
        return uri.startsWith("/pay");
    }

    private void respondWithForbidden(HttpServletResponse response, ErrorCode error) throws IOException {
        // 设置响应内容类型为 JSON
        response.setContentType("application/json; charset=UTF-8");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 设置状态码为 403 禁止访问

        try (PrintWriter out = response.getWriter()) {
            out.print(Result.failed(error).toJsonString());
            out.flush();
        }
    }
}
